package cn.itxc.demo.service.impl;

import cn.itxc.demo.service.IZookeeperService;
import com.google.common.base.Charsets;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by Gavin on 2017/6/20.
 */
@Service
public class ZookeeperServiceImpl implements IZookeeperService {

    private static Logger LOGGER = LoggerFactory.getLogger(ZookeeperServiceImpl.class);

    @Autowired
    private CuratorFramework curatorFramework;

    @Override
    public void addNode(String path, String value) {
        try {
            //创建先
//            curatorFramework
            curatorFramework.create().withMode(CreateMode.PERSISTENT).forPath(path, value.getBytes(Charsets.UTF_8));
        } catch (Exception e) {
            LOGGER.error("ZK Create Node , error", e);
        }
    }

    @Override
    public void deleteNode(String path) {
        try {
            curatorFramework.delete().forPath(path);
        } catch (Exception e) {
            LOGGER.error("Delete zk data error ", e);
        }
    }

    @Override
    public void updateNode(String path, String value) {
        try {
            deleteNode(path);
            addNode(path, value);
        } catch (Exception e) {
            LOGGER.error("Update zk data error ", e);
        }
    }

    @Override
    public String getNode(String path) {
        try {
            return new String(curatorFramework.getData().forPath(path));
        } catch (Exception e) {
            LOGGER.error("Fetch zk data error ", e);
        }
        return null;
    }
}
